import java.util.Arrays;

public class Heap {
    public int[] elem;
    public int usedSize;

    public Heap() {
        this.elem=new int[10];
    }

    public void initElem(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i]=array[i];
            usedSize++;
        }
    }

    public void createHeap() {
        for (int parent = (usedSize-1-1)/2; parent >=0 ; parent--) {
            shiftDown(parent,usedSize);
        }
    }

    private void shiftDown(int parent,int len) {
        int child=2*parent+1;
        while (child<len){
            if(child+1<len&&elem[child]>elem[child+1]){
                child++;
            }
            if(elem[parent]>elem[child]){
                swap(elem,parent,child);
                parent=child;
                child=parent*2+1;
            }else {
                break;
            }
        }
    }
    private void swap(int[] array,int i,int j){
        int tmp=array[i];
        array[i]=array[j];
        array[j]=tmp;
    }

    public void push(int val) {
        if(isFull()){
            elem= Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize++]=val;
        shiftUp(usedSize-1);
    }

    private void shiftUp(int child) {
        int parent=(child-1)/2;
        while (child>0){
            if(elem[child]<elem[parent]){
                swap(elem,child,parent);
                child=parent;
                parent=(child-1)/2;
            }else{
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize==elem.length;
    }

    public void pollHeap() {
        if(isEmpty()){
            return;
        }
        swap(elem,0,usedSize-1);
        usedSize--;
        shiftDown(0,usedSize);
    }

    public boolean isEmpty() {
        return usedSize==0;
    }

    public int peekHeap() {
        if(isEmpty()){
            return -1;
        }
        return elem[0];
    }

    public void show(){
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }
}
